﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using PiCamera;
using PiFramework;
using PiUi.View;



namespace PiUi.Froms
{
    public partial class HomeUi : BaseView
    {
        List<string> ListProject = null;

        public HomeUi()
        {
            InitializeComponent();
            PNotificationCenter.DefaultCenter().AddObserver("PLoger", this.OnNotification);
            PNotificationCenter.DefaultCenter().AddObserver("sendImage", this.OnNotification);
            PNotificationCenter.DefaultCenter().AddObserver("sendData", this.OnNotification);
            PModelControlHelp.Instance().loadProjectPath();
            ListProject = PModelControlHelp.Instance().GetProjectList();
            comboBox1.Items.AddRange(ListProject.ToArray());
        }
        /// <summary>
        /// 递归遍历指定控件及其所有子控件
        /// </summary>
        /// <param name="parent">父控件</param>
        private void TraverseControls(Control parent)
        {
            foreach (Control ctrl in parent.Controls)
            {
                // 例如：输出控件的名称和类型
                // Console.WriteLine($"控件名称: {ctrl.Name}, 类型: {ctrl.GetType().Name}");

                if (ctrl.GetType() == typeof(System.Windows.Forms.Button))
                {
                    System.Windows.Forms.Button btn = (System.Windows.Forms.Button)ctrl;
                    btn.BackColor = ThemeColor.PrimaryColor;
                    btn.ForeColor = Color.White;
                    btn.FlatAppearance.BorderColor = ThemeColor.SecondaryColor;

                }

                if (ctrl.GetType() == typeof(GroupBox))
                {

                    GroupBox gb = (GroupBox)ctrl;
                    gb.ForeColor = ThemeColor.PrimaryColor;
                    gb.Font = new System.Drawing.Font("微软雅黑", 10, FontStyle.Bold);
                    //   gb.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                }

                if (ctrl.GetType() == typeof(Label))
                {
                    Label label = (Label)ctrl;
                    label.ForeColor = ThemeColor.SecondaryColor;
                    label.Font = new System.Drawing.Font("微软雅黑", 13, FontStyle.Bold);
                }
                if (ctrl.GetType() == typeof(System.Windows.Forms.ComboBox))
                {
                    System.Windows.Forms.ComboBox cb = (System.Windows.Forms.ComboBox)ctrl;
                    cb.ForeColor = ThemeColor.PrimaryColor;

                }
                // 如果当前控件包含子控件，递归调用
                if (ctrl.Controls.Count > 0)
                {
                    TraverseControls(ctrl);
                }
            }
        }

        public override void LoadTheme()
        {
            TraverseControls(this);
            label1.ForeColor = Color.White;
        }

        private void tableLayoutPanel4_Paint(object sender, PaintEventArgs e)
        {
        }


        private void CreatePieChart()
        {
            // 设置 Series1 的类型为饼状图

            chart1.Series["Series1"].ChartType = SeriesChartType.Column; // 改为柱状图
                                                                         // chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true; // 启用 3D 效果
                                                                         //chart1.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 15; // 上下倾斜角度
                                                                         //chart1.ChartAreas["ChartArea1"].Area3DStyle.Rotation = 20; // 旋转角度

            // 清空旧数据，防止重复添加
            chart1.Series["Series1"].Points.Clear();
            // 添加数据
            chart1.Series["Series1"].Points.AddXY("OK", 1);
            chart1.Series["Series1"].Points.AddXY("NG", 1);

            chart1.Series["Series1"].Points[0].Color = Color.Green;
            chart1.Series["Series1"].Points[1].Color = Color.Red;

            // 显示数据标签（百分比）
            chart1.Series["Series1"].IsValueShownAsLabel = true;

            // 让标签显示在外部，并添加连接线
            chart1.Series["Series1"]["PieLabelStyle"] = "Outside";
            chart1.Series["Series1"]["PieLineColor"] = "Black";

            // 设置起始角度
            chart1.Series["Series1"]["PieStartAngle"] = "270";
        }


        private void HomeUi_Load(object sender, EventArgs e)
        {
            LoadTheme();
            CreatePieChart();
        }
        private const int MaxLogLines = 1000; // 设置最大日志行数
        Color color = Color.Black;
        public void OnNotification(string name, object sender, Dictionary<string, object> userInfo)
        {
            if (this.IsHandleCreated)
            {

                if (name == "PLoger")
                {
                    string message = userInfo["message"].ToString();
                    string level = userInfo["level"].ToString();


                    if (level == "INFO")
                    {
                        color = Color.Blue;

                    }
                    else if (level == "WARNING")
                    {
                        color = Color.DarkOrange;

                    }
                    else if (level == "ERROR")
                    {
                        color = Color.Red;
                    }
                    Invoke(new Action(() =>
                    {
                        richTextBoxLoger.SelectionColor = color;
                        // 使用 AppendText 添加日志信息
                        richTextBoxLoger.AppendText(message + Environment.NewLine);

                        // 限制日志的最大行数，超过时只保留最新的 MaxLogLines 行
                        if (richTextBoxLoger.Lines.Length > MaxLogLines)
                        {
                            var lines = richTextBoxLoger.Lines;
                            // 从后面截取最新的 MaxLogLines 行
                            var newLines = new string[MaxLogLines];
                            Array.Copy(lines, lines.Length - MaxLogLines, newLines, 0, MaxLogLines);
                            richTextBoxLoger.Lines = newLines;
                        }
                        // 将光标移动到文本末尾，使滚动条保持在底部
                        richTextBoxLoger.SelectionStart = richTextBoxLoger.Text.Length;
                        richTextBoxLoger.ScrollToCaret();
                    }));
                }

                if (name == "sendImage")
                {

                    if (userInfo.ContainsKey("souImage"))
                    {

                        Bitmap imageSou = (Bitmap)userInfo["souImage"];

                        Invoke(new Action(() =>
                        {
                            pShowImage1.Image = imageSou;
                        }));
                    }
                    if (userInfo.ContainsKey("resImage"))
                    {
                        Bitmap imageRes = (Bitmap)userInfo["resImage"];
                        Invoke(new Action(() =>
                        {
                            pShowImage2.Image = imageRes;
                        }));
                    }
                }

                if (name == "sendData")
                {


                    if (userInfo.ContainsKey("OKnum") && userInfo.ContainsKey("NGnum"))
                    {
                        int ok = Convert.ToInt32(userInfo["OKnum"]);
                        int ng = Convert.ToInt32(userInfo["NGnum"]);
                        chart1.Series["Series1"].Points.Clear();
                        // 添加数据
                        chart1.Series["Series1"].Points.AddXY("OK", ok);
                        chart1.Series["Series1"].Points.AddXY("NG", ng);
                        chart1.Series["Series1"].Points[0].Color = Color.Green;
                        chart1.Series["Series1"].Points[1].Color = Color.Red;

                    }
                }

            }
        }

        private bool isRun = false;
        private void button1_Click(object sender, EventArgs e) //循坏运行
        {

            if (!isRun)
            {
                string model = comboBox1.Text;
                if (model == "")
                {
                    MessageBox.Show("请选择测试型号");
                    return;
                }
                PSysConfigVar.Instance.Display();



                int m_ThreadSpeed = Convert.ToInt32(PSysConfigVar.Instance.GetConfigVar("sysConfig.ThreadSpeed"));

                PJintThreadControl.Instance.AllThreadRun(m_ThreadSpeed);
                isRun = true;
                //修改UI状态
                label1.Text = "运行中";
                this.buttonRun.Image = global::PiUi.Properties.Resources.stop;
                label1.BackColor = Color.Green;
            }
            else
            {
                this.buttonRun.Image = global::PiUi.Properties.Resources.run;
                PJintThreadControl.Instance.AllThreadStop();
                isRun = false;
                label1.Text = "已停止";
                label1.BackColor = Color.Red;
                PCameraControlHelp.Instance.StopGrab("NorCamera"); // 停止相机
            }
        }

        private async void buttonRunOne_Click(object sender, EventArgs e) // 单步运行
        {
            isRun = true;
            PJintThreadControl.Instance.AllThreadStop();
            //修改UI状态
            label1.Text = "运行中";
            this.buttonRun.Image = global::PiUi.Properties.Resources.stop;
            label1.BackColor = Color.Green;
            string model = comboBox1.Text;
            if (string.IsNullOrEmpty(model))
            {
                MessageBox.Show("请选择测试型号");
                return;
            }


            isRun = true;
            PJintThreadControl.Instance.AllThreadRun(200,1);

            // 在后台线程检查线程状态，避免阻塞 UI
            await Task.Run(async () =>
            {
                while (!PJintThreadControl.Instance.AllThreadisStop())  // 等待线程运行完成
                {
                    await Task.Delay(100); // 避免高 CPU 占用
                }
            });

            // 线程运行完成后，更新 UI
            isRun = false;
            this.Invoke(new Action(() =>
            {
                this.buttonRun.Image = global::PiUi.Properties.Resources.run;
                label1.Text = "已停止";
                label1.BackColor = Color.Red;
            }));

            PJintThreadControl.Instance.AllThreadStop(); // 确保线程完全停止
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            PJintThreadControl.Instance.AllThreadDelete();
            PModelControlHelp.Instance().setModel(comboBox1.Text);
            Dictionary<string, object> userInfo = new Dictionary<string, object>();
            userInfo.Add("comboBoxName", comboBox1.Text);
            PNotificationCenter.DefaultCenter().PostNotification("ChangeComboBox", new object(), userInfo);
        }
    }
}
